﻿using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Syspetro.Deploy.Managers;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace Syspetro.Deploy.Jwt
{
    /// <summary>
    /// 私钥模式授权
    /// </summary>
    public class JwtHSService : IJwtService
    {
        #region Option注入
        readonly ITokenCache Cache;
        private readonly JwtTokenOptions _JWTTokenOptions;
        readonly IAuthorizationManager _authorization;
        public JwtHSService(IOptionsMonitor<JwtTokenOptions> jwtTokenOptions, ITokenCache tokenCache, IAuthorizationManager authorization)
        {
            this._JWTTokenOptions = jwtTokenOptions.CurrentValue;
            Cache = tokenCache;
            _authorization = authorization;
            Cache.ExpireTimeSpan = new TimeSpan(0, _JWTTokenOptions.ExpiredTime, 0);
        }
        #endregion
        /// <summary>
        /// 创建Token
        /// </summary>
        /// <param name="userModel"></param>
        /// <returns></returns>
        public (Guid, string) GetToken(IUserAuth userModel)
        {
            if (string.IsNullOrEmpty(userModel.RoleName))
            {
                userModel.RoleName = "-";
                userModel.IsAdmin = false;
            }
            var claims = new[]
            {
                   new Claim(ClaimTypes.Name, userModel.UserName),
                   new Claim(ClaimTypes.Role, userModel.RoleName),
                   new Claim("Account", userModel.Account),
                   new Claim("Level", userModel.Level.ToString()),
                   new Claim("Emil", userModel.Emil ?? ""),
                   new Claim("Phone", userModel.Phone ?? ""),
                   new Claim("IsAdmin", userModel.IsAdmin.ToString()),
                   new Claim("UserId", userModel.UserId.ToString())
            };
            var token = CreateToken(claims);
            Serilog.Log.Information("用户登录：" + userModel.UserName);
            if (_JWTTokenOptions.ExpiredRefresh > 0)
            {
                var id = Guid.NewGuid();
                Cache.Add(userModel.UserId, id, token);
                return (id, token);
            }
            else
            {
                return (Guid.Empty, token);
            }
        }
        /// <summary>
        /// 刷新Token
        /// </summary>
        /// <param name="tokenId"></param>
        /// <returns></returns>
        public string RefreshToken(Guid tokenId)
        {
            var token = Cache.GetByToken(tokenId);
            if (token != null)
            {
                var clims = JWTEncryption.GetPrincipalFromAccessTokenHs(token, _JWTTokenOptions);
                if (clims != null)
                {
                    var newtoken = CreateToken(clims.Claims);
                    Cache.Refresh(tokenId, newtoken);
                    return newtoken;
                }
            }
            return null;
        }
        /// <summary>
        /// 生成Token
        /// </summary>
        /// <param name="claims"></param>
        /// <returns></returns>
        private string CreateToken(IEnumerable<Claim> claims)
        {
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(this._JWTTokenOptions.IssuerSigningKey));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            /**
            Claims 部分包含了一些跟这个 token 有关的重要信息。 
            JWT 标准规定了一些字段，下面节选一些字段:
            iss: The issuer of the token，token 是给谁的
            sub: The subject of the token，token 主题
            exp: Expiration Time。 token 过期时间，Unix 时间戳格式
            iat: Issued At。 token 创建时间， Unix 时间戳格式
            jti: JWT ID。针对当前 token 的唯一标识
            **/
            var time = _JWTTokenOptions.ExpiredTime;
            if (_JWTTokenOptions.ExpiredRefresh > 0)
                time = _JWTTokenOptions.ExpiredRefresh;
            if (time <= 0)
                time = 5;
            var token = new JwtSecurityToken(
            issuer: this._JWTTokenOptions.ValidIssuer,
            audience: this._JWTTokenOptions.ValidAudience,
            claims: claims,
            expires: DateTime.Now.AddMinutes(time),
            notBefore: DateTime.Now,//开始生效的时间(意味着在这个时间之前验证JWT是会失败的)
            signingCredentials: creds);
            return new JwtSecurityTokenHandler().WriteToken(token);
        }
        /// <summary>
        /// 移除Token
        /// </summary>
        /// <param name="tokenId"></param>
        /// <returns></returns>
        public void RemoveToken(Guid tokenId)
        {
            var userid = _authorization.GetUserId;
            Cache.RemoveByUser(userid,tokenId);
        }
    }
}
